<?php
tsLoad('/core/CoreLib/AbstractMysqlPage.class.php');
class RecommendUserPage extends AbstractMysqlPage {
	
	public function upgrade($params){
		tsLoad('/manage/busi/UserBusi.class.php');
		$userBusi = new UserBusi();
		global $mysqlTools;
		$mysqlTools->startTransaction();
		$result=$this->upgradeMember($params);
		//升级用户角色
		if($result == "success"){
			//$userBusi->upgradeUserTree($params['userId']);
			$mysqlTools->commitTransaction();
		}else{
			$mysqlTools->rollback();
		}	
		return $result;
	}
		
	
	/**
	 * 升级用户
	 */
	 public function upgradeMember($params){
	 	$userinfo = $this->getuserInfo($params);
	 	if($params['userGold']>$userinfo[0]['userGold']-1000){
	 		return "fail";
	 	}
	 	//更改用户状态
	 	$result = $this->updateUserState($params);
	 	if(!$result){
	 		return "fail";
	 	}
    	$uniqid = getCurrentId();
    	
    	$params['sysProInId']=$uniqid;
    	$myuniqid = getCurrentId();
    	$usuniqid = getCurrentId();

	 	
	 	//减少自己的野猪币
	 	//$result= $this->updateUserGold($params['myuserId'],$userinfo[0]['userGold']-$params['userGold']);
	 	$sysProInMo=$params['userGold'];
	 	//增加系统用户收益表
	 	//扣除给钱人的钱
 	 	$this->addUserincomeRmo($myuniqid,$params['userGold'], $sysProInMo, 6, 9, $params['myuserId'], 2, $usuniqid, $uniqid,0);
  		//增加得钱人的钱
  		if($params['sysProInReason']==1 ||$params['sysProInReason']==2)
 	 		$this->addUserincomeRmo($usuniqid,1000, 1000, 6, 6, $params['userId'], 1, $myuniqid, $uniqid,0);
  			
  		
  		$params['myuserId']=$params['userId'];
 		$userinfo=$this->getuserInfo($params);
 		//给报单用户分5%
 		//if($params['sysProInReason']!=3){
 		//	$userinfo = $this->getuserInfo($params);
 			if(!empty($userinfo[0]['userCenterUserId'])){
 				$sysProInMo= $this->addUserincomeRmo(getCurrentId(),$params['userGold'], $sysProInMo, 4,$params['sysProInReason'], $userinfo[0]['userCenterUserId'],1, null, $uniqid,0);
 			}
 		//}
		//为指定收益人给予提成
    	$queryIncomeUserId=$this->getSysBenUserId();
    	//增加系统用户收益表
     	$sysProInMo=$this->addUserincomeRmo(getCurrentId(),$params['userGold'], $sysProInMo, 5,$params['sysProInReason'], $queryIncomeUserId[0]['sysBenUserId'],1, null, $uniqid,$queryIncomeUserId[0]['sysBenPer']);
	 	//分钱
	 	if(empty($userinfo[0]['userRecom1UserId'])){
	 		$params['sysProInMo']=$sysProInMo;
	 		//给用户10级内的推荐人分钱
	 		$getMo = $this->tenRecomUserOnePercent($params['userId'], ((int)$params['userGold'])*0.01, $uniqid);
	 		$params['sysProInMo']=$params['sysProInMo']-$getMo;
	 		$mos =  $this->addSysProfit($params);
	 		if($mos){
	 			return "success";
	 		}else{
	 			return "fail";
	 		}
	 	}
	 		$sysProInMo= $this->addUserincomeRmo(getCurrentId(),$params['userGold'], $sysProInMo, 1,$params['sysProInReason'], $userinfo[0]['userRecom1UserId'],1, null, $uniqid,0);
	 		if($sysProInMo==0){
	 			return "fail";
	 		}
	 	if(empty($userinfo[0]['userRecom2UserId'])){
	 		$params['sysProInMo']=$sysProInMo;
	 		//给用户10级内的推荐人分钱
	 		$getMo = $this->tenRecomUserOnePercent($params['userId'], ((int)$params['userGold'])*0.01, $uniqid);
	 		$params['sysProInMo']=$params['sysProInMo']-$getMo;
	 		$asp =  $this->addSysProfit($params);
	 		if($asp){
	 			return "success";
	 		}else{
	 			return "fail";
	 		}
	 	}
		 	//给二级推荐人分钱
			$sysProInMo= $this->addUserincomeRmo(getCurrentId(),$params['userGold'], $sysProInMo, 2,$params['sysProInReason'], $userinfo[0]['userRecom2UserId'],1, null, $uniqid,0);
	 		if($sysProInMo==0){
	 			return "fail";
	 		}
	 	
	 	if(empty($userinfo[0]['userRecom3UserId'])){
	 		$params['sysProInMo']=$sysProInMo;
	 		//给用户10级内的推荐人分钱
	 		$getMo = $this->tenRecomUserOnePercent($params['userId'], ((int)$params['userGold'])*0.01, $uniqid);
	 		$params['sysProInMo']=$params['sysProInMo']-$getMo;
	 		$adpf =  $this->addSysProfit($params);
	 		if($adpf){
	 			return "success";
	 		}else{
	 			return "fail";
	 		}
	 	}
	 		//给三级推荐人分钱
	 		$sysProInMo= $this->addUserincomeRmo(getCurrentId(),$params['userGold'], $sysProInMo, 3,$params['sysProInReason'], $userinfo[0]['userRecom3UserId'],1, null, $uniqid,0);
	 		if($sysProInMo==0){
	 			return "fail";
	 		}
	 		
	 	$params['sysProInMo']=$sysProInMo;
	 	//给用户10级内的推荐人分钱
	 	$getMo = $this->tenRecomUserOnePercent($params['userId'], ((int)$params['userGold'])*0.01, $uniqid);
	 	$params['sysProInMo']=$params['sysProInMo']-$getMo;
	 	
	 	
	 	$r =  $this->addSysProfit($params);
	 	if($r){
	 		return "success";
	 	}else{
	 		return "fail";
	 	}
	 }
	 
	 /**
	  * 添加用户收入明细表
	  * $level 收入人类型 userInFType 1.一级推荐人 2.二级推荐人 3.三级推荐人 4.被报单 5.指定收益人 6.其他
	  * $userInFReason  1.升级为会员 2.直接升级为报单中心用户 3.普通用户升级为报单用户 4作为报单用户获得5% 5.指定收益人获得5% 6.他人赠送 7.赠送给他人 8.提现 9.野猪币消费
	  */
	 public function addUserincomeRmo($uniqid,$gold,$sysProInMo,$level,$userInFReason,$userId,$userInFZf,$userInFReId,$sysProInId,$sysBenPer){
	 	global $roleuser;
	 	$roleuser['userId']=$userId;
	 	$userRole= $this->getRoleByUserId($roleuser);
	 	$roleuser['userInFUserId']=$userId;
	 	$roleuser['uniqid']=$uniqid;
	 	$roleuser['userInFZf']=$userInFZf;
	 	$roleuser['userInFLoginId']=$userRole[0]['userLoginId'];
	 	$roleuser['userInFType']=$level;
	 	$roleuser['userInFReId']=$userInFReId;
	 	$roleuser['sysProInId']=$sysProInId;
	 	$roleuser['roleId']=$userRole[0]['roleId'];
	 	$roleuser['roleDesc']=$userRole[0]['roleDesc'];
	 	$roleuser['userInFReason']=$userInFReason;
	 	if($level==4){
	 		$userGold=$gold*0.05;
	 		$roleuser['userInFMo']=$userGold;
	 	}elseif ($level==5){
		 	$userGold=$gold*($sysBenPer/100);
	 	}else{
		 	$userGold=$gold*$this->getRebateLevel($level);
	 	}
	 	
	 	if($userInFReason<4&&$level<4){
	 		$roleuser['userInFOthMo']=$gold*$this->getRoleLevel($userRole[0]['roleLevel']);
	 		$userGold=$userGold+$gold*$this->getRoleLevel($userRole[0]['roleLevel']);
	 	}else{
	 		$roleuser['userInFOthMo']=0;
	 	}
	 	$roleuser['userInFMo']=$userGold;
	 	
	 	$muserGold=$userRole[0]['userGold'];
	 	if($userInFZf==1){
	 		$muserGold=$userRole[0]['userGold']+$userGold;
	 	}else{
	 		$muserGold=$userRole[0]['userGold']-$userGold;
	 	}
	 	
	 	$this->updateUserGold($userId,$muserGold);
	 	$roleuser['userInFSurGlod']=$muserGold;
	 	if(!$this->addUserIncome($roleuser)){
	 		return "0";
	 	}
	 	return $sysProInMo-$userGold;
	 }
	 
	 /**
	  * 根据推荐人等级返利
	  * @param unknown $level
	  * @return number
	  */
	 public function getRebateLevel($level){
	 	//1:一級推荐人 2:二級推荐人 3:三級推荐人
	 	switch ($level){
	 		case 1:
	 			return  0.15;
	 		case 2:
	 			return  0.1;
	 		case 3:
	 			return  0.08;
	 		default:
	 			return 1;
	 	}
	 }
	 /**
	  * 根据角色等级返利
	  * @param unknown $level
	  * @return number
	  */
	 public function getRoleLevel($level){
	 	//1:普通会员 2:销售代表 3:主管 4：经理  5：总经理 6:股东 
	 	switch ($level){
		 	case 1:
		 		return  0;
		 	case 2:
		 		return  0.01;
		 	case 3:
		 		return  0.02;
		 	case 4:
		 		return  0.03;
		 	case 5:
		 		return  0.04;
		 	case 6:
		 		return  0.05;
		 	default:
		 		return 0;
	 	}	 	
	 }
	
	
	/**
	 * 取得总的行数
     */
    public function calTotalRows ()
    {
      
    	global $mysqlTools;
        $condition = $mysqlTools->check_input($this->condition,array('userLoginId','userRecom1LoginId','userRecom2LoginId','userRecom3LoginId'));
   
        
       	$sqlCore = "
        	SELECT 
			    COUNT(*) AS totalCount
			FROM
			 sys_user su
       		left join sys_user_role sur  on su.userId=sur.userId
    		left join sys_role sr on  sr.roleId=sur.roleId
        ";
        
        $where = "
         	WHERE 1=1
           AND sr.roleType=2
        ";
        
    	//用户信息查询
        if(!empty($condition['contact'])){
        	$where.= ' AND  (`su`.`userEmail` = '.$condition['contact'].
        	' OR `su`.`userTel` = '.$condition['contact'].
        	' OR `su`.`userPhone` = '.$condition['contact'].
        	' OR `su`.`userQQ` = '.$condition['contact'].' )';
        }
        
        //用户名查询
        if(!empty($condition['myuserId'])){
        	$where.= ' AND  su.userId != '.$condition['myuserId'];
        	$where.= ' AND  (su.userRecom1UserId ='.$condition['myuserId'];
        	$where.= ' OR su.userRecom2UserId ='.$condition['myuserId'];
        	$where.= ' OR su.userRecom3UserId ='.$condition['myuserId'].')';
        }

        
        
        //用户名查询
        if(!empty($condition['userLoginId'])){
        	$where.= ' AND  su.userLoginId LIKE '.$condition['userLoginId'];
        }
        //一级推荐
        if(!empty($condition['userRecom1LoginId'])){
        	$where.= ' AND  su.userRecom1LoginId LIKE '.$condition['userRecom1LoginId'];
        }
        
        //二级推荐
        if(!empty($condition['userRecom2LoginId'])){
        	$where.= ' AND  su.userRecom2LoginId LIKE '.$condition['userRecom2LoginId'];
        }
        
        //三级推荐
        if(!empty($condition['userRecom3LoginId'])){
        	$where.= ' AND  su.userRecom3LoginId LIKE '.$condition['userRecom3LoginId'];
        }
        
        //查看状态
        if(!empty($condition['userState']) && $condition['userState']!=5){
        	$where.= ' AND su.userState ='.$condition['userState'];
        }
        
        //创建开始时间与结束时间
        if(!empty($condition['userCreateTimeStart'])){
        	$where.= ' AND su.userCreateTimeStart >='.$condition['userCreateTimeStart'];
        }
        if(!empty($condition['userCreateTimeEnd'])){
        	$where.= ' AND su.userCreateTimeEnd ='.$condition['userCreateTimeEnd'];
        }
        
        $sql = $sqlCore.$where;
        //总记录数
        $totalRows = $mysqlTools->selectSql($sql)[0]['totalCount'];
        
        return $totalRows;
    }

	/** 
     *取得数据集合
     */
    public function getList ($sRowNo, $pageRows)
    {
        global $mysqlTools;
        
        //保存一个原生值以便需要的时候进行处理
        $orgCondition = $this->condition;
        
        $condition = $mysqlTools->check_input($this->condition,array('userLoginId','userRecom1LoginId','userRecom2LoginId','userRecom3LoginId'));
   
        
        $sqlCore = "
        	SELECT 
		    su.userId,
		    su.userLoginId,
		    su.userPhone,
		    su.userTel,
		    su.userEmail,
		    su.userQQ,
		    su.userAvatarId,
		    su.userState,
		    su.userCreateTime,
        	su.userPassTime,
        	su.userSex,
        	su.userRecom1LoginId,
        	su.userRecom2LoginId,
        	su.userRecom3LoginId,
        	su.userIsCenterUser,
        	su.userState,
        	su.userGold,
        	sr.roleDesc
		FROM
		    sys_user su
    		left join sys_user_role sur  on su.userId=sur.userId
    		left join sys_role sr on  sr.roleId=sur.roleId
        ";
        
        $where = "
         	WHERE 1=1
        	AND sr.roleType=2
        ";
        
        //用户名查询
        if(!empty($condition['userLoginId'])){
        	$where.= ' AND  su.userLoginId LIKE '.$condition['userLoginId'];
        }
        //用户信息查询
        if(!empty($condition['contact'])){
        	$where.= ' AND  (`su`.`userEmail` = '.$condition['contact'].
        	' OR `su`.`userTel` = '.$condition['contact'].
        	' OR `su`.`userPhone` = '.$condition['contact'].
        	' OR `su`.`userQQ` = '.$condition['contact'].' )';
        }
        
        //用户名查询
        if(!empty($condition['myuserId'])){
        	$where.= ' AND  su.userId != '.$condition['myuserId'];
        	$where.= ' AND  (su.userRecom1UserId ='.$condition['myuserId'];
        	$where.= ' OR su.userRecom2UserId ='.$condition['myuserId'];
        	$where.= ' OR su.userRecom3UserId ='.$condition['myuserId'].')';
        }
        
    
        //一级推荐
        if(!empty($condition['userRecom1LoginId'])){
        	$where.= ' AND  su.userRecom1LoginId LIKE '.$condition['userRecom1LoginId'];
        }
        
        //二级推荐
        if(!empty($condition['userRecom2LoginId'])){
        	$where.= ' AND  su.userRecom2LoginId LIKE '.$condition['userRecom2LoginId'];
        }
        
        //三级推荐
        if(!empty($condition['userRecom3LoginId'])){
        	$where.= ' AND  su.userRecom3LoginId LIKE '.$condition['userRecom3LoginId'];
        }
        //查看状态
        if(!empty($condition['userState']) && $condition['userState']!=5){
        	$where.= ' AND su.userState ='.$condition['userState'];
        }
        
        //创建开始时间与结束时间
        if(!empty($condition['userCreateTimeStart'])){
        	$where.= ' AND su.userCreateTimeStart >='.$condition['userCreateTimeStart'];
        }
        if(!empty($condition['userCreateTimeEnd'])){
        	$where.= ' AND su.userCreateTimeEnd ='.$condition['userCreateTimeEnd'];
        }
        $order = "";
        if(!empty($orgCondition['order'])&&!empty($orgCondition['sort'])){
        	$order = " ORDER BY su.".$orgCondition['sort']." ".$orgCondition['order']." ";
        }else{
	        $order = " ORDER BY `su`.`userCreateTime` DESC ";
        }
        $limit = " LIMIT $sRowNo,$pageRows";
        $sql = $sqlCore.$where.$order.$limit;
        
        //查询角色信息分页
        $list = $mysqlTools->selectSql($sql);
        
        return $list;
    }
    
    
    /**
     * 更改用户状态
     */
    public function updateUserState($condition){
    	global $mysqlTools;
    	//保存一个原生值以便需要的时候进行处理
    	$condition = $mysqlTools->check_input($condition);
    	try {
    		$sql = "UPDATE `sys_user` SET `userId` = `userId`";
    		if(!empty($condition['userState']) && $condition['userState']!=0){
    			$sql.= ",`userState` = $condition[userState]";
    		}
    		if(!empty($condition['userIsCenterUser']) && $condition['userIsCenterUser']!=0){
    			$sql.= ",`userIsCenterUser` = $condition[userIsCenterUser]";
    		}
    		if(!empty($condition['sysProInReason']) && $condition['sysProInReason']!=3){
    			$sql.= ",`userPassTime` = now()";
    		}
    		$sql.=" where `userId` = $condition[userId]";
    		if(!empty($condition['userState']) && $condition['userState']!=0){
    			$sql.= " AND `userState` = 4";
    		}
    		if(!empty($condition['userIsCenterUser']) && $condition['userIsCenterUser']!=0){
    			$sql.= " AND `userIsCenterUser` = 2";
    		}
    		$result = $mysqlTools->executeSql($sql);
    	} catch (\Exception $e) {
    		return "false";
    	}
    	return $result;
    }

    /**
     * 根据用户ID得到用户信息
     */
    public function getuserInfo($condition){
    	global $mysqlTools;
    	$condition = $mysqlTools->check_input($condition);
    	  $sql = "
        	SELECT 
		    su.userGold,
    	  	su.userRecom1UserId,
    	  	su.userRecom1LoginId,
    	  	su.userRecom2UserId,
    	  	su.userRecom2LoginId,
    	  	su.userRecom3UserId,
    	  	su.userRecom3LoginId,
    	  	su.userCenterUserId,
    	    su.userCenterLoginId
		FROM
		    sys_user su
    	  WHERE 1=1
        ";
    	 //用户名查询
    	 if(!empty($condition['myuserId'])){
    	 	$sql.= ' AND  su.userId = '.$condition['myuserId'];
    	 }
    	  
    	  //查询角色信息分页
    	  $userinfo = $mysqlTools->selectSql($sql);
    	  return $userinfo;
    }
    
    /**
     * 根据用户ID得到角色详细
     */
    public function getRoleByUserId($condition){
    	global $mysqlTools;
    	$condition = $mysqlTools->check_input($condition);
    	$sql = "
        	SELECT
		    sr.roleId,
    		sr.roleName,
    		sr.roleType,
    		sr.roleLevel,
    		sr.roleDesc,
    		s.userGold,
    		s.userLoginId
		FROM
		    sys_role sr
    		left join sys_user_role su  on su.roleId=sr.roleId
    		left join sys_user s on s.userId=su.userId
    	  WHERE 1=1
        ";
    	//用户名查询
    	if(!empty($condition['userId'])){
    		$sql.= ' AND  su.userId = '.$condition['userId'];
    	}
    	 
    	//查询角色信息分页
    	$role = $mysqlTools->selectSql($sql);
    	return $role;
    }
    
    
    /**
     * 修改野猪币
     */
    public function updateUserGold($myuserId,$userGold){
    	global $mysqlTools;
    	try {
    		$sql = "UPDATE `sys_user` SET `userId` = `userId`".",`userGold` = ".$userGold." where `userId` = ".$myuserId;
    		$result = $mysqlTools->executeSql($sql);
    	} catch (\Exception $e) {
    		return "false";
    	}
    	return $result;
    }
    
    
    /**
     * 添加野猪币
     */
    public function addUserGold($myuserId,$userGold){
    	global $mysqlTools;
    	try {
    		$sql = "UPDATE `sys_user` SET `userId` = `userId`".",`userGold` =`userGold` + ".$userGold." where `userId` = ".$myuserId;
    		$result = $mysqlTools->executeSql($sql);
    	} catch (\Exception $e) {
    		return "false";
    	}
    	return $result;
    }
    
    
    
    /**
     * 添加系统收益表
     */
    public function  addSysProfit($condition){
    	global $mysqlTools;
    	//生成唯一ID
  
    	$sql="insert into sys_profit_info(sysProInId,sysProInCreatetime,sysProInReason,sysProInMo) values($condition[sysProInId],now(),$condition[sysProInReason],$condition[sysProInMo]);";
    	$result = $mysqlTools->executeSql($sql);
    	return $result;
    }
    /**
     * 添加用户收入明细表
     */
    public function  addUserIncome($condition){
    	global $mysqlTools;
    	$sql="insert into user_bop_info(userInFId,userInFZf,userInFUserId,userInFLoginId,userInFCreatetime,userInFType,userInFMo,roleId,roleDesc,userInFOthMo,userInFReason";
    	if(!empty($condition['userInFReId'])){
    		$sql.= ",userInFReId";
    	}
    	$sql.=",sysProInId,userInFSurGlod) values";
    	$sql.="($condition[uniqid],$condition[userInFZf],$condition[userInFUserId],'$condition[userInFLoginId]',now(),$condition[userInFType],$condition[userInFMo],'$condition[roleId]','$condition[roleDesc]',$condition[userInFOthMo],$condition[userInFReason]";
    	if(!empty($condition['userInFReId'])){
    		$sql.= ",$condition[userInFReId]";
    	}
    	$sql.=",$condition[sysProInId],$condition[userInFSurGlod]);";
    	$result = $mysqlTools->executeSql($sql);
    	return $result;
    }
    
    /**
     * 得到受益人的ID
     */
    public function  getSysBenUserId(){
    	global $mysqlTools;
    	$sql="select sysBenUserId,sysBenPer from sys_set limit 0,1";
    	$result = $mysqlTools->selectSql($sql);
    	return $result;
    }
    
    /**
     * 为10级内的用户增加1%的佣金
     */
    public function tenRecomUserOnePercent($userId,$getMo,$sysProInId){
    	global $mysqlTools;
    	tsLoad('/manage/busi/UserBusi.class.php');
    	$userBusi = new UserBusi();
    	$tenLevelUsers = $userBusi->findTenLevelUserByUserId($userId);
    	
    	//总计消耗金额
    	$lossMo = 0;
    	foreach ($tenLevelUsers as $i=>$tenLevelUser)
    	{
    		//为推荐的用户每人加入1%的收入
    		$recomSql = "
    		update sys_user set userGold=userGold+$getMo where userId = $tenLevelUser[userId]
    		";
    		$mysqlTools->executeSql($recomSql);
    		$tenUserInFId = getCurrentId();
    		//增加收支明细记录
    		$userBopInfoSql = "
    		insert into user_bop_info(userInFId,userInFZf,userInFUserId,userInFLoginId,userInFCreatetime,userInFType,
    		userInFMo,roleId,roleDesc,userInFOthMo,userInFReason,userInFReId,withdId,sysProInId,userInFSurGlod
    		) values(
    		$tenUserInFId,1,$tenLevelUser[userId],'$tenLevelUser[userLoginId]',now(),7,$getMo,$tenLevelUser[roleId],
    		'$tenLevelUser[roleDesc]',0,12,0,0,$sysProInId,$tenLevelUser[userGold]+$getMo
    		)
    		";
    		$mysqlTools->executeSql($userBopInfoSql);
    
    		$lossMo = $lossMo+$getMo;
    	}
    	return $lossMo;
    }
    
}	

?>